
require 'cgi'

require 'appwiki/base/base_request.rb'

#
# TODO BROKEN UNUSED
#
@@cookiez = "hi"
@@requestcount = 0

class BaseRequestModProxy < BaseRequest

    ##########################################################################
    # init
    ##########################################################################

    def initialize(r)

      @cgi = CGI.new

      @status = 200
      @method = ENV['REQUEST_METHOD'].downcase #works
      @method = r.request_method.downcase if !@method #works
      @content_type = 'text/html'

      @referer = nil
      @referer = @cgi.referer if @cgi.referer
      @referer = @cgi.header['Referer'] if !@referer
      @referer = r.headers_in['Referer'] if !referer
      @params = H.new
      @cgi.params.each do |x,y|
        # cgi can be a string or if pre 1.8.x an array, or a hash
        # if encoded then can be a TempFile or a StringIO if len < 10240
        # kind_of? Array kind_of? StringIO kind_of? TempFile
        if "#{y.class}" == "Array" && y.length > 0
          y = y[0]
        end
        if y.kind_of? String
          # good
        elsif y.kind_of?(StringIO)||y.kind_of?(File)|| "#{y.class}"=="Tempfile"
          if x == "depiction"
            # cgi:: is inconsistent; make it consistent
            # also, if the field is actually in fact empty then do not forward.
            next if !y.original_filename || y.original_filename.to_s.length < 1
            #@params["#{x}_original_filename"] = "#{y.original_filename}"
          else
            y = y.read
          end
        end
        @params[x] = y
      end 
      @@requestcount = @@requestcount + 1
      @@cookiez = cookie = @cgi.cookies['anselm_sid']
      @k = H.new
      if !cookie
        @@cookiez = "no cookie #{cookie}"
      elsif "#{cookie.class}" == "Array"
        @@cookiez = "was an array of length #{cookie.length}"
        cookie = cookie[0] if cookie.length > 0
      elsif "#{cookie.class}" == "String"
        @cookiez = "was a string #{cookie}"
        @k = kp(cookie)
      elsif "#{cookie.class}" == "CGI::Cookie"
        cookie = cookie.to_s
        @@cookiez = "was a cgi cookie #{cookie}" 
        @k = kp(cookie)
      end
      @cookies = @k.dup
      @@cookiez = "#{@@cookiez} request count is #{@@requestcount}"

      @host = r.hostname
      @request_uri = self
      @host = @@forcehostname if defined?(@@forcehostname) && @@forcehostname != nil
      @path = r.uri

      @r = r
      @headers_out = H.new 

    end

    def set_redirect(value)
      #@r.status = 303
      #@r.headers_out['Location'] = value
      @cgi.out( 
         "status" => "303",
         "Location" => value 
        ) { "" }
    end

    def set_content_type(value)
      @content_type = value
    end

    def set_body(body)
      # fails
      # @r.headers_out['content-type'] = @content_type if @content_type
      # @r.headers_out['content-length'] = body.length

      # fails
      #@r.write "HTTP/1.1 200 OK\r\n"
      #@r.write "Status: 200 OK\r\n"   
      #@r.write "Content-Length: #{body.length}\r\n" if body
      #@r.write "Content-Type: text/html\r\n\r\n"

      domainbase = @host.split('.')[-2..-1].join('.')
      cookies = @cookies.map { |k,v|
         "#{k}=#{escape(v)};Domain=.xxxfixmexxx.org;Path=/" if v != @k[k] 
      }.compact
     
      c = "#{cookies}"
 
      @cgi.out(
          #"nph" => true,
          "status" => "OK",
          "connection" => "close",
          "type" => @content_type,
          "expires" => Time.now,
          #"cache-control" => 'no-cache',
          #"pragma" => 'no-cache',
          "cookie" => [c] 
          ) { body }

      # xxx could write custom headers too

    end

    def set_cookies
      #domainbase = @host.split('.')[-2..-1].join('.')
      #value = @cookies.map { |k,v|
      #   "#{k}=#{escape(v)}; domain=.#{domainbase};  path=/" if v != @k[k] 
      #}.compact
      ## fails
      # @r.headers_out['Set-Cookie'] = value
    end

    def []=(a,b)
      # fails @r.headers_out[a]=b
      @headers_out[a] = b
    end

    def [](a) 
      # fails @r.headers_out[a]
      @headers_out[a]
    end

    def body=(value)
      # fails
      # @r.write value
    end

    def method_missing(m,*a)
      logmsg "base_mod_proxy: method not found!!! #{m}"
      exit
    end

end

#
# call this from mod proxy to do one request
# the base_config include should have opened activerecord etc
#
def appwiki_dorequest(r)
  # this fails logmsg "doing request #{r.uri}"
  Dir.chdir @@webfiles if @@webfiles
  req = BaseRequestModProxy.new r
  @@routes.each do |route|
    return true if route.resolve(req,req,nil)
  end
  return false
end

